﻿namespace JwiKIDE.Controls
{
    using System;
    using System.IO;
    using System.Windows.Forms;

    public partial class TextDocument : UserControl
    {
        private bool dirty = false;
        public event EventHandler DocumentDirty;
        public string TextAsString
        {
            get
            {
                return tbEditor.Text;
            }
        }

        public bool Dirty
        {
            get
            {
                return dirty;
            }
        }

        public bool FirstSave { get; private set; }

        public string FileName { get; private set; }
        public TextDocument()
        {
            InitializeComponent();
            FirstSave = false;
        }
        public TextDocument(string fileName)
        {
            FileName = fileName;
            this.InitializeComponent();
            FirstSave = true;
        }
        public void SaveToFile(string fileName)
        {
            using(TextWriter tw = new StreamWriter(fileName))
            {
                tw.Write(tbEditor.Text);
                FileName = fileName;
            }
            FirstSave = false;
            dirty = false;
        }
        public void SaveToFile()
        {
            using (TextWriter tw = new StreamWriter(FileName))
            {
                tw.Write(tbEditor.Text);
            }
            FirstSave = false;
            dirty = false;
        }
        public void LoadFromFile(string fileName)
        {
            using(TextReader tr = new StreamReader(fileName))
            {
                tbEditor.Text = tr.ReadToEnd();
                FileName = fileName;
            }
           
        }

        private void tbEditor_KeyPress(object sender, KeyPressEventArgs e)
        {
            if(!dirty)
                OnDocumentDirty();
            dirty = true;
        }

        private void OnDocumentDirty()
        {
            if (DocumentDirty != null) DocumentDirty(this,null);
        }

    }
}
